<?php
/**
 * Autoloader class
 * @author Kirill Egorov
 */
class Autoloader
{
    static protected $_paths = array();
    static protected $_classMap = array();
    static protected $_packagesConfig = array();
    static protected $_debugData = array();
    static protected $_usePackage = false;
    static protected $_useMap = false;
    /**
     * Debug mode
     * @var boolean
     */
    static public $debug = false;
    /**
     * Register library path
     * @param string $path
     * @return void
     */
    static public function registerPath($path)
    {
        if(!in_array($path , self::$_paths))
             self::$_paths[] = $path;
    }
    /**
     * Register library paths
     * @param array $paths
     */
    static public function registerPaths(array $paths)
    {
    	if(empty($paths))
    		return;
    	foreach ($paths as $path)
    		self::registerPath($path);
    }
    /**
     * Load class 
     * @param string $class
     * @return boolean
     */
    public static function load($class)
    {       
        if(self::$_useMap && array_key_exists($class , self::$_classMap))
        {     
        	/*
        	 * Try to load package
        	 */
        	if(strlen(self::$_classMap[$class]['package'] && self::$_usePackage))
        	{
        		$name = self::$_classMap[$class]['package'];
        		if(isset(self::$_packagesConfig['packages'][$name]) && self::$_packagesConfig['packages'][$name]['active'])
        		{
        			require_once self::$_packagesConfig['path'] . $name . '.php'; 
        			return true;
        		}	        		
        	}
            /*
             * Try to load from map   
             */          
            require_once self::$_classMap[$class]['file'];    
            if(self::$debug)
                self::$_debugData[] = $class;       
            return true;
        }

        /*
         * Search for class file
         */
        $file = implode(DIRECTORY_SEPARATOR , array_map('ucfirst',explode('_', $class))) . '.php';
            
        foreach(self::$_paths as $path)
        {         
           if(file_exists($path . DIRECTORY_SEPARATOR . $file)){
                require_once $path . DIRECTORY_SEPARATOR . $file;
                if(self::$debug)
                    self::$_debugData[] = $class;  
                return true;
           }
        }
        return false;
    }
   /**
    * Load class map
    * @property array $path
    * @return array
    */ 
   static public function loadMap(array $data) {
        self::$_classMap = $data;
        self::$_useMap = !empty($data);
   } 
   /**
    * Load packages config and start using packages
    * @param array $data
    */
   static public function loadPackagesConfig(array $data){
   		self::$_packagesConfig = $data;
   		self::$_usePackage = !empty($data);
   }
   /**
    * Debug function. Shows loaded class files
    * @return array
    */
   static public function getLoadedClasses(){
       return self::$_debugData;
   }
}